﻿using System;
using System.Data;
using System.Windows.Forms;
using Home.Haushalt.Lib;
using Infragistics.Win.UltraWinCalcManager.FormulaBuilder;
using System.Drawing;
using Home.Haushalt.Lib.Element;
using Infragistics.Win.UltraWinGrid;
using Infragistics.Win;
using System.Collections.Generic;
using System.Linq;

namespace Home.Haushalt.Gui
{
    /// <summary>
    /// 
    /// </summary>
    public partial class UcGridFormMain : UcGridForm
    {
        private UcGridForm ucSideGridForm;

        /// <summary>
        /// 
        /// </summary>
        public UcGridFormMain()
            : base(DefaultColumnSets.GridDefault, DefaultColumnSets.GridDefault.ToString())
        {
            InitializeComponent();

            BaseGrid.ContextMenuStrip.Opened += new EventHandler(ContextMenuStrip_Opened);

            //Nebengrid initialisieren
            ucSideGridForm = UcGridForm.Instatiate(DAO.Settings.Selected.SideGrid);

            if (ucSideGridForm != null)
            {
                ucSideGridForm.LayoutName = DAO.Settings.Selected.SideGridLayout;

                ucSideGridForm.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
                | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right)));
                ucSideGridForm.Location = new System.Drawing.Point(3, 3);
                ucSideGridForm.Name = "ucGridForm";
                ucSideGridForm.Size = new System.Drawing.Size(425, 502);
                ucSideGridForm.TabIndex = 1;
                Controls.Add(ucSideGridForm);
                Controls.SetChildIndex(ucSideGridForm, 0);

                ucSideGridForm.OnStatusChanged += new EventHandler<HEventArgs>(grid_OnStatusMessage);
            }
            else
            {
                Journal.Add(this, ActionResult.Nok, "Nebengrid \"" + DAO.Settings.Selected.SideGrid + "\" konnte nicht geladen werden");
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void FrmGridForm_Load(object sender, EventArgs e)
        {
            if (!LayoutController.IsInDesignMode(this))
            {
                BaseGrid.DataBind(FinAccount.ElementType, ColumnSet);
                BaseGrid.LoadLayout(LayoutName);

                //ucGridFormMonthbalance.DataBind(DateTime.Now.Year, DateTime.Now.Month, true);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ContextMenuStrip_Opened(object sender, EventArgs e)
        {
            if (BaseGrid._clickedObject is UltraGridCell || BaseGrid._clickedObject is UltraGrid)
            {
                if (BaseGrid.ContextMenuCopyElementItem != null)
                    BaseGrid.ContextMenuCopyElementItem.Visible = false;
                if (BaseGrid.ContextMenuDeleteElementItem != null)
                    BaseGrid.ContextMenuDeleteElementItem.Visible = false;
                if (BaseGrid.ContextMenuNewElementItem != null)
                    BaseGrid.ContextMenuNewElementItem.Visible = false;
                if (BaseGrid.ContextMenuPropertySeparatorItem != null)
                    BaseGrid.ContextMenuPropertySeparatorItem.Visible = false;
                if (BaseGrid.ContextMenuPropertySeparator2Item != null)
                    BaseGrid.ContextMenuPropertySeparator2Item.Visible = false;
                if (BaseGrid.ContextMenuParentPostenElementItem != null)
                    BaseGrid.ContextMenuParentPostenElementItem.Visible = false;
                if (BaseGrid.ContextMenuParentOpponentElementItem != null)
                    BaseGrid.ContextMenuParentOpponentElementItem.Visible = false;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void grid_DoubleClickRow(object sender, Infragistics.Win.UltraWinGrid.DoubleClickRowEventArgs e)
        {
            if (BaseGrid.Selected.Rows.Count > 0)
            {
                BaseGrid.EditElementProperty();
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cmnuPropertyEdit_Click(object sender, EventArgs e)
        {
            foreach (UltraGridRow row in BaseGrid.Selected.Rows)
            {
                BaseGrid.EditElementProperty();
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cmnuPropertyNew_Click(object sender, EventArgs e)
        {
            BaseGrid.EditElementProperty(ElementBase.Instantiate(FinAccount.ElementType).New().Row);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cmnuPropertyCopy_Click(object sender, EventArgs e)
        {
            foreach (UltraGridRow row in BaseGrid.Selected.Rows)
            {
                BaseGrid.EditElementProperty(row.ToDataRow().Clone());
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cmnuPropertyCopySerie_Click(object sender, EventArgs e)
        {
            foreach (UltraGridRow row in BaseGrid.Selected.Rows)
            {
                DataRow newRow = row.ToDataRow().Clone();

                if (newRow[Posten.Fields.SerieId].ToInt() == -1)
                {
                    newRow[Posten.Fields.SerieId] = Posten.GetNextSerieId();
                }

                BaseGrid.EditElementProperty(newRow);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cmnuPropertyDelete_Click(object sender, EventArgs e)
        {
            if (LO.Message("Confirm.DeleteSelectedEntries", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                BaseGrid.DeleteRows(BaseGrid.SelectedRows);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnUpdateSelectedKontos_Click(object sender, EventArgs e)
        {
            BaseGrid.ActiveRow = null;
            BaseGrid.Selected.Rows.Clear();

            BaseGrid.Enabled = btnUpdateAllKontos.Enabled = btnUpdateSelectedKontos.Enabled = false;

            bwBanking.RunWorkerAsync(sender);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void bwBanking_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            bool updateAll = (sender == e.Argument);

            foreach (UltraGridRow gridRow in BaseGrid.Rows)
            {
                FinAccount accountObj = new FinAccount(gridRow.ToDataRow());

                accountObj.LastChangedCount = 0;

                if (updateAll || gridRow.Cells[FinAccount.Fields.Updating].Value.ToBool(false))
                {
                    bwBanking.ReportProgress(0, accountObj.Name);

                    accountObj.UpdateDates();
                }
            }

            DAO.SaveFinAccount();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void bwBanking_ProgressChanged(object sender, System.ComponentModel.ProgressChangedEventArgs e)
        {
            OnStatusChangedApply(new HEventArgs(LO.Status("LoadOnlineAccountData", e.UserState.ToString())));
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void bwBanking_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
        {
            //Tabellen refreshen
            WindowController.RefreshGrids(FinAccount.ElementType);
            WindowController.RefreshGrids(FinDate.ElementType);

            //Saldo aktualisieren
            DAO.MonthbalanceCollection.DataBind();
            WindowController.RefreshMonthbalanceGrids();

            OnStatusChangedApply(new HEventArgs(LO.Status("Ready")));

            BaseGrid.Enabled = btnUpdateAllKontos.Enabled = btnUpdateSelectedKontos.Enabled = true;
        }

        private Dictionary<string, UcGridFormElement> _finDateGrids = new Dictionary<string, UcGridFormElement>();

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BaseGrid_ClickCell(object sender, ClickCellEventArgs e)
        {
            //foreach (UcGridFormElement ucEl in _finDateGrids.Values)
            //{
            //    ucEl.Visible = false;
            //}

            //FinAccount finAccount = (FinAccount)ElementBase.Instantiate(e.Cell.Row.ToDataRow());
            //ElementBase finDate = new FinDate(finAccount);

            //string key = finAccount.ID.ToString();

            //UcGridFormElement gridFinDate = null;

            //if (!_finDateGrids.ContainsKey(key))
            //{
            //    gridFinDate = new UcGridFormElement(finDate, DefaultColumnSets.TabDefault, DefaultColumnSets.TabDefault.ToString());
            //    _finDateGrids.Add(key, gridFinDate);

            //    pnlFinDataGrid.Controls.Add(gridFinDate);
            //    gridFinDate.Dock = DockStyle.Fill;
            //    gridFinDate.BaseGrid.DisplayLayout.CaptionVisible = DefaultableBoolean.False;
            //    gridFinDate.DataBind();
            //}
            //else
            //{
            //    gridFinDate = _finDateGrids[key];
            //}


            //gridFinDate.Visible = true;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BaseGrid_AfterRowActivate(object sender, EventArgs e)
        {
            foreach (UcGridFormElement ucEl in _finDateGrids.Values)
            {
                ucEl.Visible = false;
            }

            FinAccount finAccount = (FinAccount)ElementBase.Instantiate(BaseGrid.ActiveRow.ToDataRow());
            ElementBase finDate = new FinDate(finAccount);

            string key = finAccount.ID.ToString();

            UcGridFormElement gridFinDate = null;

            if (!_finDateGrids.ContainsKey(key))
            {
                gridFinDate = new UcGridFormElement(finDate, DefaultColumnSets.TabDefault, DefaultColumnSets.TabDefault.ToString());
                _finDateGrids.Add(key, gridFinDate);

                pnlFinDataGrid.Controls.Add(gridFinDate);
                gridFinDate.BaseGrid.AllowExpertFilter(this.components);
                gridFinDate.Dock = DockStyle.Fill;
                gridFinDate.BaseGrid.DisplayLayout.CaptionVisible = DefaultableBoolean.False;
                gridFinDate.DataBind();
            }
            else
            {
                gridFinDate = _finDateGrids[key];
            }


            gridFinDate.Visible = true;

        }

        private void pnlFinDataGrid_Paint(object sender, PaintEventArgs e)
        {

        }

    }
}
